
import PageView from '../../../static/sys/js/view/PageView'

import _ from 'underscore'

var Detail = PageView.extend({
  area: "Detail",

  initialize: function () {
    window.yyesn.client.setHeader({title:"预定详情",navColor:"#FD746E"});

    this.$el.on("click", ".detail-btn-item", this.applyRoom.bind(this));

    this.$el.on("click", ".icon-add", this.selectContacts.bind(this));

    this.contactsList = [];
    this.userInfo = window._userInfo || {};

    this.randomc = ["#29d4ff", "#1594ff", "#ffa92f", "#b587fa", "#06cf86", "#fa6771", "#73d51c", "#8991ff"];
  },
  didRender: function () {
    this.detailHeaderEl = this.el.querySelector(".detail-head");
    this.detailUlEl = this.el.querySelector(".detail-member-ul");

    this.loadingEl = this.el.querySelector(".loading-wrapper");

    //render
    this.renderApplyUser();

  },
  onResume: function () {
    window.yyesn.client.setHeader({title:"预定详情",navColor:"#FD746E"});
    //初始化单页的区域滚动
    R('.mui-scroll-wrapper').scroll({
       indicators: false,
       deceleration: 0.0001
    });
    //render
    this.contactsList = [];
    this.renderApplyUser();
  },
  renderApplyUser: function () {
    if (window._userInfo) {
      this.contactsList.push(window._userInfo);
      this.renderContacts();
    }

  },
  renderContacts: function () {
    var elHtml = [];
    for (var i = 0; i < this.contactsList.length; i++) {
      var each = this.contactsList[i];
      var li = `
        <li>
          <img src="`+ each.avatar+`">
        </li>
        `
      if (!each.avatar) {
        var randomc = this.randomc[+_.random(0, 7)];
        var name = each.name.length > 2 ? each.name.substring(1) : each.name;
        li = `
          <li>
              <span class=default-avatar style=background:`+ randomc +`>`+ name +`</span>
          </li>
          `
      }
      elHtml.push(li);
    }
    elHtml.push(`<li><span class="icon-add"></span></li>`)
    this.detailUlEl.innerHTML = elHtml.join("");

  },
  selectContactsEnd: function (data) {
    if (data.error_code == 0) {
      // alert(JSON.stringify(data));
      this.contactsList = data.data;
      // var index = _.findIndex(this.contactsList, function(each){ return each.id == 123})
      // if (index == -1) {
      //   this.contactsList.push(this.applyUser)
      // }
      this.renderContacts();
    }
  },
  selectContacts: function () {
    var self = this;
    window.yyesn.enterprise.selectContacts(function(data){
      // alert(JSON.stringify(data));
      self.selectContactsEnd(data);
    }, {
       nav_title: '选择联系人',
       nav_color: '#FD746E',
       select_list: self.contactsList
    })
  },
  postRoute: function (options) {
    if (options) {
      this.routeParam = options;
      this.renderHeader(options);
      this.renderNum(options);
    }
  },
  renderNum: function (options) {
    var max = options.curentRoom.roommum;
    this.$el.find(".num").attr("max", max);
    this.$el.find(".num").attr("placeholder", "人数("+max+"人以内)");
  },
  calculatePrice:function (cost,stime, endtime, day) {
    stime = (day + " " + stime).replace(/-/g,"/");
    endtime = (day + " " + endtime).replace(/-/g,"/");
    var bookHour = (Date.parse(endtime) - Date.parse(stime)) / (60*60*1000);
    // console.log(bookHour);
    return +cost * bookHour
  },
  renderHeader: function (options) {
    var day = options.timeData.time.substring(options.timeData.time.indexOf("-")+1);
    var time = options.timeData.Stime + "-" +  options.timeData.Etime;
    this.totalPrice = this.calculatePrice(options.curentRoom.cost, options.timeData.Stime, options.timeData.Etime, options.timeData.time);
    this.totalPrice = /(^[1-9]\d*$)/.test(this.totalPrice) ? this.totalPrice : this.totalPrice.toFixed(1) ;

    var html = `
      <div>
        <span class="detail-title">` + options.curentRoom.room + `</span>
        <span class="detail-money">合计:￥`+ this.totalPrice +`元</span>
      </div>
      <div class="detail-capacity"> `+ day + ` `+ time+`
      </div>
    `
    this.detailHeaderEl.innerHTML = html;
  },

  getAttendee: function () {
    return _.map(this.contactsList, function (each) {
      return each.email || "";
    })
  },
  applyRoom: function () {
    var number = this.el.querySelector(".num").value;
    var details = this.el.querySelector("[name=details]").value;
    var theme = this.el.querySelector("[name=theme]").value;
    var phone = this.userInfo.mobile || "", account = this.userInfo.email || "", email = this.userInfo.email || "";
    var attendee = this.getAttendee();


    if (!theme) {
      R.toast('请填写会议主题');
      return;
    }
    if (theme && theme.length > 30) {
      R.toast('主题字数超过限制');
      return;
    }
    if (!/^[0-9]*[1-9][0-9]*$/.test(number) && number && number !="0") {
      R.toast('请输入正确的人数');
      return;
    }

    if (+number > +this.routeParam.curentRoom.roommum) {
      R.toast('人数超过限制');
      return;
    }

    var obj = {
      roomID: this.routeParam.curentRoom.roomID,
      time:   this.routeParam.timeData.time,
      Stime: this.routeParam.timeData.Stime,
      Etime: this.routeParam.timeData.Etime,
      number: number,
      details:details,
      phone: phone,
      account: account,
      email: email,
      attendee:attendee,
      total: this.totalPrice,
      theme: theme
    }
    var options = {
      service:"applyRoom",
      data:obj,
      success:function(res){
        console.log(res);
        R.loading(-1);

        this.el.querySelector(".num").value = "";
        this.el.querySelector("[name=details]").value = "";
        this.el.querySelector("[name=theme]").value = "";

        R.toast(res, 1600, function () {
          this.appPush(theme, details);
        }.bind(this));
      }.bind(this),
      error:function(res){
        console.log(res);
        R.loading(-1);
        if (res.error && /被预定/.test(res.error.errormsg)) {
          R.toast(res.error.errormsg);
        } else {
          R.toast('预约失败');
        }

      }.bind(this)
    }
    console.log(options);
    R.loading();
    application.sendAjax(options);
  },
  getTo: function () {
    return _.map(this.contactsList, function (each) {
      return each.member_id;
    })
  },
  appPush: function (theme, details) {
    var to = this.getTo();
    details = this.userInfo.name + "邀请你于" + this.routeParam.timeData.time + " " +  this.routeParam.timeData.Stime + "参加" + theme+ "会议, 地点" + this.routeParam.curentRoom.room + ", 记得准时参加喔"

    $.ajax({
      url:"/symeetingbook/meeting/sengMsg",
      type:"POST",
      data:{
        to: to,
        title: "会议通知",
        desc: details,
        detailUrl: ""
      },
      timeout:6000,
      success: function (res) {
        console.log(res);
        if (res.code == 0) {
          R.toast('已成功通知参会人员', function () {
            this.navigate("NewIndex");
          }.bind(this));
        } else {
          this.navigate("NewIndex");
        }

      }.bind(this),
      error: function (res) {
        console.log(res);
        this.navigate("NewIndex");
      }.bind(this)

    })
  }

})





export default Detail
